import { Component, ChangeDetectorRef, ChangeDetectionStrategy, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AnalystViewModel } from '../../templates/analystView/analystView.model';
import { CompanyRiskRatingService } from '../../companyRiskRating.service';
import { Subscription } from 'rxjs';
import { ClusterService } from '../../../../riskCluster/cluster.service';

/**
 * MEI analyst view component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'mei-analyst-view',
    templateUrl: '../../templates/analystView/analystView.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../templates/analystView/analystView.component.scss'
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AnalystViewMeiComponent extends AnalystViewModel {
    private sub: Subscription;
    private companySub: Subscription;
    private meiSub: Subscription;
    public exposure: number;
    public management: number;
    public manageableRisk: number;
    public managedRisk: number;
    public exposureCode: string;
    public managementCode: string;
    public meiIsMain: boolean;
    public exposureAssesment: string;
    public managementAssesment: string;
    public intervalExposurechartColors: string[];
    public intervalManagementchartColors: string[];
    public finalBetaFactor: string;
    public subindustryExposureScore: number;
    public meiIsBaselineIssue: boolean;

    @Input() displayType = 'distribution';

    constructor(
        private route: ActivatedRoute,
        private cdRef: ChangeDetectorRef,
        private riskService: CompanyRiskRatingService,
        private clusterService: ClusterService) {
        super(cdRef);
        this.isMei = true;
        this.intervalExposurechartColors = ['#CCCCCC', '#F9DE94', '#F6CD5C'];
        this.intervalManagementchartColors = ['#CCCCCC', '#E6F5F5', '#7CD0CE'];
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.load();
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
        if (this.companySub) this.companySub.unsubscribe();
        if (this.meiSub) this.meiSub.unsubscribe();
    }

    private load(): void {
        this.exposureCode = this.managementCode = this.manageableRisk = undefined;
        this.exposureCode = this.managementCode = this.manageableRisk = this.exposure = this.management = undefined;
        this.cdRef.markForCheck();
        this.loaded = new Promise<void>((resolve, reject) => {
            this.companySub = this.riskService.company.subscribe(company => {
                this.meiSub = this.riskService.mei.subscribe(mei => {
                    this.meiIsMain = mei.isMain;
                    // To do: refactor all these conditions using ifs 
                    this.analystViewExposureAssessment = mei.comments.analystViewExposureAssessment ? mei.comments.analystViewExposureAssessment : "";
                    this.exposureComment = (this.meiIsMain ? (mei.comments.exposure ? mei.comments.exposure : "") : "") + (this.analystViewExposureAssessment != null ? this.analystViewExposureAssessment : "");

                    this.analystViewManagementAssessment = mei.comments.analystViewManagementAssessment ? mei.comments.analystViewManagementAssessment : "";
                    this.managementComment = (this.meiIsMain ? (mei.comments.management ? mei.comments.management : "") : "") + (this.analystViewManagementAssessment != null ? this.analystViewManagementAssessment : "");

                    this.narrative = mei.narrative ? mei.narrative : "";

                    this.meiIsBaselineIssue = (mei.type == 'BaselineIssue') ? true : false;
                    this.exposure = mei.exposure;
                    this.subindustryExposureScore = mei.subindustryExposureScore;
                    this.management = mei.management;
                    this.manageableRisk = mei.manageableRisk;
                    this.managedRisk = mei.managedRisk;
                    this.finalBetaFactor = mei.finalBetaFactor.toFixed(2);
                    this.cdRef.markForCheck();

                    // exposure clusters
                    this.clusterService.exposure.subscribe(clusters => {
                        if (clusters.length > 0)
                            clusters[clusters.length - 1].topInterval = 20;
                        this.exposureClusters = clusters;
                        this.exposureClusters.forEach((cluster, index) => {
                            if (!this.exposureCode && this.exposure - cluster.topInterval <= 0.01) {
                                this.exposureCode = index.toString();
                                this.exposureAssesment = cluster.shortName || cluster.name;
                            }
                        });
                        this.cdRef.markForCheck();
                        resolve();
                    });

                    // management clusters
                    this.clusterService.management.subscribe(clusters => {
                        this.managementClusters = clusters;
                        this.managementClusters.forEach((cluster, index) => {
                            if (this.management - cluster.topInterval <= 0.01) {
                                this.managementCode = index.toString();
                                this.managementAssesment = cluster.shortName || cluster.name;
                            }
                        });
                        this.cdRef.markForCheck();
                        resolve();
                    });

                    this.cdRef.markForCheck();
                    resolve();
                }, error => this.errorCallback(_ => this.errorReset(), undefined));
            });
        });
    }

    get maxExposure() {
        return "20+";
    }

    get maxManagement() {
        return 100;
    }
}